package com.twb.log.queue;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.twb.log.entity.twbLogOperation.TwbLogOperation;
import com.twb.log.service.ITwbLogOperationService;

/**
 * @Title LogConsumer.java
 * @Description 日志的保存线程
 * 
 * @author DSY
 * @date 2017年5月25日 下午2:41:42
 */
@Component("logConsumer")
public class LogConsumer implements Runnable {

	private static Logger logger = LoggerFactory.getLogger(LogConsumer.class);

	@Autowired
	private ITwbLogOperationService twbLogOperationService;
	@Autowired
	private LogQueue logQueue;

	public static final int DEFAULT_BATCH_SIZE = 100;
	private int batchSize = DEFAULT_BATCH_SIZE;
	private boolean active = true;
	private Thread thread;

	@PostConstruct
	public void init() {
		thread = new Thread(this);
		thread.start();
	}

	@PreDestroy
	public void close() {
		active = false;
	}

	@Override
	public void run() {
		while (active) {
			execute();
		}
	}

	public void execute() {
		List<TwbLogOperation> list = new ArrayList<TwbLogOperation>();

		try {
			int size = 0;

			while (size < batchSize) {
				TwbLogOperation logOperation = logQueue.poll();

				if (logOperation == null) {
					break;
				}

				list.add(logOperation);
				size++;
			}
		} catch (Exception ex) {
			logger.info(ex.getMessage(), ex);
		}

		if (!list.isEmpty()) {
			twbLogOperationService.saveBatch(list); // 持久化日志到数据库
		}
	}

	public void setBatchSize(int batchSize) {
		this.batchSize = batchSize;
	}
}
